module Key2LED (
    // 50MHz
    input sys_clk,
    // reset
    input sys_rst_n,
    // input keys,0:key0,1:key1
    input [1:0] keys,
    // 0:led0,1:led1
    output reg [1:0] led
);

// 0.5s max count,20ns/tick,-1 because start index 0
parameter MaxCount=25'd25_000_000-25'd1;
// 100ns
// parameter MaxCount=25'd5-25'd1;

// current ticks
reg [24:0] curTickCount;
/*
0: no press any key,all LED turn off
01: key0 pressed,FlowLED work
10: key1 pressed,LEDs the same blink
*/
reg [1:0] curState;

// counter
always @(posedge sys_clk,negedge sys_rst_n)begin
    if(!sys_rst_n) curTickCount<=25'b0;
    else begin
        // not press any key
        if(keys==2'b11)begin
            if(curTickCount>=MaxCount)curTickCount<=25'd0;
            else curTickCount<=curTickCount+1;
        end else
            // reset tick count
            curTickCount<=25'd0;
    end
end

// update state
always @(posedge sys_clk,negedge sys_rst_n)begin
    // reset state
    if(!sys_rst_n)curState<=2'b0;
    else begin
        case (keys)
            2'b01:begin
                curState<=2'b01;
            end
            2'b10:begin
                curState<=2'b10;
            end
            default:curState<=curState; 
        endcase
    end
end

// state mechine
always @(posedge sys_clk,negedge sys_rst_n)begin
    // reset state
    if(!sys_rst_n)led<=2'b0;
    else begin
        case(curState)
            2'b00: led<=2'b00;
            2'b01: begin
                // flow LED
                // make sure led state is suit flow
                if(led!=2'b01 && led!=2'b10)
                    led<=2'b01;
                else if(curTickCount==MaxCount)
                    led<={led[0],led[1]};
                else
                    led<=led;
            end
            2'b10: begin
                // synchro blink
                // make sure led state is suit blink
                if(led!=2'b00 && led!=2'b11)
                    led<=2'b00;
                else if(curTickCount==MaxCount)
                    led<=~led;
                else
                    led<=led;
            end
        endcase
    end
end

endmodule
